package cn.qqncn.email;

import com.sun.mail.util.MailSSLSocketFactory;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;

/**
 * @author zkw
 * @Description TODO
 * @createTime 2021年05月08日 13:42:00
 */
public class EmailUtils {
    private static final String MY_EMAIL = "415477041@qq.com";
    private static final String EMAIL_KEY = "aitualmcyxhxbjjb";

    /**
     *
     * @param to_email 接收邮箱
     * @param content  邮件内容
     * @param from_date 来自【多少时间】  比如：2020年1月25日13时25分
     * @return
     * @throws GeneralSecurityException
     * @throws MessagingException
     */
    public static String senEmail(String to_email,String content,String from_date) throws GeneralSecurityException, MessagingException {
        Properties props = new Properties();

        // 开启debug调试
        props.setProperty("mail.debug", "true");
        // 发送服务器需要身份验证
        props.setProperty("mail.smtp.auth", "true");
        // 设置邮件服务器主机名
        props.setProperty("mail.host", "smtp.qq.com");
        // 发送邮件协议名称
        props.setProperty("mail.transport.protocol", "smtp");

        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        props.put("mail.smtp.ssl.enable", "true");
        props.put("mail.smtp.ssl.socketFactory", sf);

        Session session = Session.getInstance(props);

        Message msg = new MimeMessage(session);
        //邮件标题
        msg.setSubject("你收到了一个时间胶囊");
        //邮件正文
        StringBuilder builder = new StringBuilder();
        builder.append(content);
        builder.append("  --------- 来自"+from_date+"的你");
        msg.setText(builder.toString());

        //发送人邮箱
        msg.setFrom(new InternetAddress(MY_EMAIL));

        Transport transport = session.getTransport();
        transport.connect("smtp.qq.com", MY_EMAIL, EMAIL_KEY);

        transport.sendMessage(msg, new Address[] { new InternetAddress(to_email) });
        transport.close();
        return "";
    }
}
